import storage from 'store'
import { login, logout, getInfo, getnoTodoNumber,getUnReadNum } from '@/api/login'
import { ACCESS_TOKEN, CURRENT_PROJECT } from '@/store/mutation-types'
import notification from 'ant-design-vue/es/notification'
import { i18nRender } from '@/locales'
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    pms: [],
    menus: [],
    info: {},
    noTodoNumber: 0, // 待办中心未读数量
    unReadNum: 2,
    // project.status 1 未启动 2 进行中 3 已关闭
    project: null,
    classify: 1 // 入账管理 区分 1表示正式，2表示测试
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NOTODONUMBER: (state, noTodoNumber) => {
      state.noTodoNumber = noTodoNumber
    },
    SET_UNREADNUM: (state, unReadNum) => {
      state.unReadNum = unReadNum
      console.log(unReadNum,state)

    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_PMS: (state, pms) => {
      state.pms = pms
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_PROJECT: (state, project) => {
      state.project = project
    },
    SET_CLASSIFY: (state, classify) => {
      state.classify = classify
    },
    UPDATE_PROJECT(state, project) {
      if (!project) return
      storage.set(CURRENT_PROJECT, JSON.stringify(project))
      storage.set('CURRENT_PROID', project.id)
      state.project = project
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const result = response
          storage.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', result.token)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
   /* eslint-disable */ 
    getNoTodoCounts({ commit }) {
      getnoTodoNumber().then(response => {
        commit('SET_NOTODONUMBER', response.todoCount)
      }).catch(error => {
      })
    },
    // 获取未读消息
    getNoReadCounts({ commit }) {
      getUnReadNum().then(response => {
        commit('SET_UNREADNUM', response.unReadNum)
      }).catch(error => {
      })
    },
    // 获取用户信息
    GetInfo({ commit }, proId) {
      // debugger

      return getInfo({
        proId: proId || ''
      }).then(response => {
        // // 此处的 userInfo 和外面的没有关系
        // const userInfo = { ...response.user }
        // // 转换后端返回的数据结构
        // userInfo.role = {
        //   permissions: response.permissions.map(({ code: permissionId, name: permissionName, id, pid, actionEntitySet, ...rest1 }) => ({
        //     permissionId,
        //     permissionName,
        //     actionEntitySet: (actionEntitySet || []).map(({ code: action, name: describe, id, pid, ...rest2 }) => ({ action, describe, ...rest2 })) ?? [],
        //     ...rest1
        //   }))
        // }
        // // console.log('userInfo', userInfo)
        // return userInfo
        response.user.isRestPwd = response.isRestPwd
        return new Promise((resolve, reject) => {
          commit('SET_PMS', response.pms)
          commit('SET_MENUS', response.menus)
          commit('SET_ROLES', response.roles)
          commit('SET_INFO', response.user)
          commit('SET_NAME', response.user.name)
          commit('SET_AVATAR', response.user.headimg)
          resolve(response.menus, response.pms)
        })
      })
      /*
      return new Promise((resolve, reject) => {
        const result = userInfo // 动态权限
        // 获取用户基本信息
        const role = result.role
        // 获取不同模块下的权限
        role.permissions = result.role.permissions
        // 返回一个新的role实例
        role.permissions.map(per => {
            // per相当于role.permissions
            // 不模块的按钮权限
          if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
            const action = []
            per.actionEntitySet.forEach(act => {
              action.push(act.action)
              if (act.actionEntitySet != null && act.actionEntitySet.length > 0) {
                act.actionEntitySet.forEach(sub => {
                  action.push(sub.code)
                })
              }
            })
            per.actionList = action
          } else {
            per.actionList = []
          }
        })
        role.permissionList = role.permissions.map(permission => { return permission.permissionId })
        commit('SET_ROLES', result.role)
        commit('SET_INFO', result)
        commit('SET_NAME', { name: result.userName, welcome: welcome() })
        commit('SET_AVATAR', result.headimg)
        localStorage.setItem('curRole', result.roleName)
        resolve(result)
        */
    },
    ClearProject({ commit }) {
      return new Promise((resolve) => {
        commit('SET_PROJECT', null)
        commit('SET_ROLES', [])
        commit('SET_PMS', [])
        commit('SET_MENUS', [])
        storage.remove(CURRENT_PROJECT)
        resolve()
      })
    },
    EnterProject({ commit }, project) {
      if (project == null) {
        return
      }
      return new Promise((resolve, reject) => {
        commit('UPDATE_PROJECT', project)
        // 重置权限 重新获取
        commit('SET_ROLES', [])
        commit('SET_PMS', [])
        commit('SET_MENUS', [])
        resolve()
      })
    },
    // 登出
    Logout({ commit, state }, payload = 0) {
      // 只有点击了确定退出按钮才调用退出接口 其他情况直接退出不调用接口
      return new Promise((resolve) => {
        if (payload) {
          logout(state.token)
            .then(() => {
              commit('SET_TOKEN', '')
              commit('SET_ROLES', [])
              commit('SET_PMS', [])
              commit('SET_MENUS', [])
              commit('SET_PROJECT', null)
              storage.remove(ACCESS_TOKEN)
              storage.remove(CURRENT_PROJECT)
              storage.remove('CURRENT_PROID')
              resolve()
            })
            .catch(() => { })
            .finally(() => { })
        } else {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PMS', [])
          commit('SET_MENUS', [])
          commit('SET_PROJECT', null)
          storage.remove(ACCESS_TOKEN)
          storage.remove(CURRENT_PROJECT)
          storage.remove('CURRENT_PROID')
          resolve()
        }
        notification.success({
          message: i18nRender('all.autotext86'),
          description: i18nRender('已退出登录')
        })
      })
    }
  }
}

export default user
